package uf.audit.db;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.json.FastJson;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import redis.clients.jedis.Jedis;
import uf.audit.util.Table;

import java.math.BigDecimal;
import java.util.*;

/**
 * 个人成绩实体
 *
 * @author sunny
 */
@Table(key = "markingbh")
public class Marking extends Model<Marking> {
    private static final long serialVersionUID = -7644540082576539659L;
    public static Marking dao = new Marking().use(DbKit.MAIN_CONFIG_NAME);
    public static HashMap<String, String> scoreDx = new HashMap<String, String>();
    public static Jedis jedis = new Jedis("127.0.0.1", 6379);

    // 容错处理 如果set的值为空，就不做处理
    public Marking set(String attr, Object value) {
        if (value != null) {
            super.set(attr, value);
        }
        return this;
    }

    // 获取得分列表（单个试卷，就返回1条）
    public List<Record> getmodelmarkings(String modelbh) {
        String sql = "select a.*, b.markingbh, b.score1, b.score2 from (select a.*, b.modelname from (select b.userbh, b.username, b.realname, a.resourcebh from (select * from authentic where resourcebh=? and authvalue=3) a left join user b on a.userbh=b.userbh) a left join testmodel b on a.resourcebh=b.modelbh) a left join marking b on a.userbh=b.userbh and a.resourcebh=b.modelbh";
        return DbPro.use().find(sql, modelbh);
    }

    // 获取得分列表（单个人员单个试卷，就返回1条）
    public List<Record> getmodelmarkings(String modelbh, String userbh) {
        String sql = "select a.*, b.markingbh, b.score1, b.score2 from (select a.*, b.modelname from (select b.userbh, b.username, b.realname, a.resourcebh from (select * from authentic where resourcebh=? and userbh=? and authvalue=3) a left join user b on a.userbh=b.userbh) a left join testmodel b on a.resourcebh=b.modelbh) a left join marking b on a.userbh=b.userbh and a.resourcebh=b.modelbh";
        return DbPro.use().find(sql, modelbh, userbh);
    }

    // 获取单个人员单个试卷
    public List<Record> getscoreopts(String modelbh, String userbh) {
        String sql = "select * from (select a.*,b.score from (select * from (select * from "
                + " testopt where testbh=(select testbh from test where userbh=? and"
                + " modelbh=? limit 1)) a where a.itemtype<>'问答题') a left join testquestion b on a.testbh=b.testbh"
                + " and a.itembh=b.itembh)a";
        return DbPro.use().find(sql, userbh, modelbh);
    }

    // 获取某个人员某个试卷的得分情况
    public Marking getmarking(String modelbh, String userbh) {
        return findFirst("select * from marking where userbh=? and modelbh=?", userbh, modelbh);
    }

    // 获取主观题的列表
    public List<Record> getcustmarking(String modelbh, String userbh) {
        String sql = "select * from (select a.*, b.optno from (select a.*, b.itemcontent "
                + " from (select a.*, b.score from (select * from (select * from testopt "
                + " where testbh=(select testbh from test where userbh=? and modelbh=? limit 1)) a where "
                + " a.itemtype<>'单选题' and a.itemtype<>'多选题' and a.itemtype<>'判断题')a left join testquestion b on a.itembh=b.itembh and "
                + " a.testbh=b.testbh) a left join question b on a.itembh=b.itembh) a "
                + " left join options b on a.optbh=b.optbh) a where a.optno='A' ";
        return DbPro.use().find(sql, userbh, modelbh);
    }

    // 单选题得分计算
    public int getsinglecheckscore(String modelbh, String userbh) {
        String sql = "select sum(score) as score from (select a.*,b.score from (select * from (select * from testopt where testbh=(select testbh from test where userbh=? and modelbh=? limit 1)) a where a.itemtype='单选题') a left join testquestion b on a.testbh=b.testbh and  a.itembh=b.itembh) a where convert(answer, SIGNED)=a.isanswer and a.isanswer=1";
        Record rec = DbPro.use().findFirst(sql, userbh, modelbh);
        BigDecimal bd = rec.getBigDecimal("score");
        int result = 0;
        if (bd != null) {
            result = bd.intValue();
        }
        return result;
    }

    // 考试题得分计算 放进redis缓存
    public void getsinglecheckscoreBySession(String modelbh, String userbh, String testbh) {
        if ("audittest".equals(userbh)) {
            Map<String, String> map = jedis.hgetAll("tourist");
            List<String> list = new ArrayList<String>();
            List<String> many = new ArrayList<String>();
            for (String key : map.keySet()) {
                String jsonstr = map.get(key);
                JSONArray jsonArray = JSONArray.parseArray(jsonstr);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject json = jsonArray.getJSONObject(i).getJSONObject("columns");//通过可以获取value//获取jsonobject
                    Record record = new Record().setColumns(FastJson.getJson().parse(json.toJSONString(), Map.class));
                    //单选题
                    if ("单选题".equals(record.getStr("itemtype")) &&
                            "1".equals(record.getStr("answer")) &&
                            record.getStr("optno").equals(record.getStr("isanswer"))
                            ) {
                        list.add(UUID.randomUUID().toString());
                    }
                    if ("多选题".equals(record.getStr("itemtype"))) {
                        if ("1".equals(record.getStr("answer")) && record.getStr("isanswer").contains(record.getStr("optno"))) {
                            many.add(UUID.randomUUID().toString());
                        }
                    }
                    if (many.size() == record.getStr("isanswer").split("、").length) {
                        list.add(UUID.randomUUID().toString());
                        many.clear();
                    }
                }
            }
            HashMap<String, String> s = new HashMap<String, String>();
            s.put("score", "" + (list.size() * 10));
            jedis.hmset("tourist^score", s);
        } else {
            List<String> doubleList = new ArrayList<String>();
            int fenshu = 0;
            int scoreOfDouble = 0;
            int doubleFenshu = 0;
            String key = "" + userbh + "^" + testbh;
            String singleAnswer = jedis.lrange(key, 0, 1000).get(0);
            JSONArray json = JSONArray.parseArray(singleAnswer);
            for (int i = 0; i < json.size(); i++) {
                JSONObject jsonObject = json.getJSONObject(i).getJSONObject("columns");
                Record record = new Record().setColumns(FastJson.getJson().parse(jsonObject.toJSONString(), Map.class));
                String itembhInRecord = record.getStr("itembh");
                String itemcontent = record.getStr("itemcontent");
                if (record.getStr("answer") == null) {
                    record.set("answer", "初始化");
                    fenshu = 0;
                }
                if (record.getStr("itemtype").equals("单选题") && record.getStr("answer").equals("1") && record.getInt("isanswer") == 1) {
                    int score = record.getInt("score");
                    fenshu += score;

                }
                if (record.getStr("itemtype").equals("多选题") && record.getStr("answer").equals("1") && record.getInt("isanswer") == 1) {
                    if (doubleList.contains(itembhInRecord)) {
                        doubleFenshu = 0;
                    } else {
                        scoreOfDouble = record.getInt("score");
                        if (doubleList.contains(itemcontent)) {
                            doubleFenshu = scoreOfDouble;
                        } else {
                            doubleList.add(itemcontent);
                            fenshu += doubleFenshu;
                        }
                    }
                } else if (record.getStr("itemtype").equals("多选题") && record.getStr("answer").equals("0") && record.getInt("isanswer") == 1) {
                    doubleList.add(itembhInRecord);
                    if (doubleList.contains(itemcontent)) {
                        doubleFenshu = 0;
                    }
                }

            }
            scoreDx.put(testbh + "singleScore" + userbh, doubleFenshu + fenshu + "");
            jedis.hmset(testbh + "singleScoreMap" + userbh, scoreDx);
            List<String> rsmap = jedis.hmget(testbh + "singleScoreMap" + userbh, testbh + "singleScore" + userbh);
            System.out.println(rsmap);
        }

    }


    // 计算所有多选题的得分<变量名命名：“计算”不应该使用get吧？>
    public int getmulticheckscore(String modelbh, String userbh) {
        int result = 0;
        String sql = "select a.itembh, a.answer, a.isanswer, score from (select a.*,b.score from (select * from (select * from testopt where testbh=(select testbh from test where userbh=? and modelbh=? limit 1)) a where a.itemtype='多选题') a left join testquestion b on a.testbh=b.testbh and  a.itembh=b.itembh) a";
        List<Record> recs = DbPro.use().find(sql, userbh, modelbh);
        Map<String, Integer> maps = new HashMap<String, Integer>();
        for (Record rec : recs) {
            String itembh = rec.getStr("itembh");
            String answer = rec.getStr("answer");
            int isanswer = rec.getInt("isanswer");
            int score = rec.getInt("score");
            Integer s = maps.get(itembh);
            if (s == null) {
                maps.put(itembh, score);
            }
            if (answer == null || answer.trim().equals("")) {
                answer = "0";
            }
            int answerInt = Integer.valueOf(answer);
            if (answerInt != isanswer) {
                maps.put(itembh, 0);
            }
        }
        Iterator<Integer> scores = maps.values().iterator();
        while (scores.hasNext()) {
            result += scores.next();
        }
        return result;
    }


    // 计算所有多选题的得分放进redis缓存
	/*public void getmulticheckscoreBySeeeion(String modelbh, String userbh,String testbh) {
		int result = 0;

		Iterator<Integer> scores = maps.values().iterator();
		while (scores.hasNext()) {
			result += scores.next();
			String multichecksResult = String.valueOf(result);
			scoreDx.put("multichecksResult",multichecksResult);
			jedis.hmset(testbh + "singleScoreMap" + userbh,scoreDx);
		}
	}*/

    // 更新
    public boolean update(JSONObject obj) {
        String bh = obj.getString("markingbh");
        Marking item = new Marking();
        item.set("userbh", obj.getString("userbh"));
        item.set("modelbh", obj.getString("modelbh"));
        item.set("score1", obj.getInteger("score1"));
        item.set("score2", obj.getInteger("score2"));
        boolean result = false;
        if (bh != null) {
            item.set("markingbh", obj.getString("markingbh"));
            result = item.update();
        } else {
            item.set("markingbh", UUID.randomUUID().toString());
            result = item.save();
        }
        return result;
    }

    // 删除
    public boolean delete(String bh) {
        return deleteById(bh);
    }

    // 计算某个人某个试卷具体的分数
    public int calcScore(String modelbh, String userbh) {
        // 开始计算客观题分数
        int single_score = getsinglecheckscore(modelbh, userbh);
        int multi_score = getmulticheckscore(modelbh, userbh);
        int result = single_score + multi_score;
        Marking marking = getmarking(modelbh, userbh);
        if (marking == null) {
            marking = new Marking();
            marking.set("userbh", userbh);
            marking.set("modelbh", modelbh);
            marking.set("score1", result);
            marking.set("markingbh", UUID.randomUUID().toString());
            marking.save();
        } else {
            marking.set("markingbh", marking.getStr("markingbh"));
            marking.set("score1", result);
            marking.update();
        }
        return result;
    }

    public boolean updateScore(String modelbh, String userbh, int score) {
        Marking marking = Marking.dao.getmarking(modelbh, userbh);
        if (marking != null) {
            marking.set("score2", score);
            return marking.update();
        }
        return false;
    }

    public List<Record> getmarkinglist(String dep, String modelbh) {
        if (dep == null) {
            String sql = "select a.*, b.levelname from (select a.*,b.seqname from (select a.*, b.orgname from (select b.username, b.realname, b.userdep, b.curlevel, b.worktype, b.workseq, IFNULL(a.score1,0) as score1, IFNULL(a.score2, 0) as score2, IFNULL(a.score1, 0)+IFNULL(a.score2, 0) as score3 from marking a LEFT JOIN user b on a.userbh = b.userbh where a.modelbh=?) a left join organize b on a.userdep = b.orgbh) a left join workseq b on a.workseq=b.seqbh) a left join worklevel b on a.curlevel=b.levelbh";
            return DbPro.use().find(sql, modelbh);
        } else {
            String sql = "select a.*, b.levelname from (select a.*,b.seqname from (select a.*, b.orgname from (select b.username, b.realname, b.userdep, b.curlevel, b.worktype, b.workseq, IFNULL(a.score1,0) as score1, IFNULL(a.score2, 0) as score2, IFNULL(a.score1, 0)+IFNULL(a.score2, 0) as score3 from marking a LEFT JOIN user b on a.userbh = b.userbh where a.modelbh=? and b.userdep = ?) a left join organize b on a.userdep = b.orgbh) a left join workseq b on a.workseq=b.seqbh) a left join worklevel b on a.curlevel=b.levelbh";
            return DbPro.use().find(sql, modelbh, dep);
        }
    }
}
